# -*- coding: utf-8 -*-

"""
@Datetime: 2019/4/16
@Author: Zhang Yafei
"""
import socket


def handle_request(client):
    request_data = client.recv(1024)
    print(request_data)
    client.send(b"HTTP/1.1 200 OK\r\n\r\n")
    # client.send(b"Hello, World")
    # client.send(b"<h1>Hello, World</h1>")
    # with open('data.txt', mode='rb') as f:
    with open('data.html', mode='rb') as f:
        response = f.read()
    print(response)
    client.send(response)


def main():
    # 1. 建立一个socket
    sock = socket.socket()
    sock.bind(('127.0.0.1', 8000))
    sock.listen(5)
    print('socket has build connection...')
    while True:
        # 2. 循环接收请求
        connection, addr = sock.accept()
        print(addr)
        # 3. 处理请求并发送
        handle_request(connection)
        # 4. 关闭当前连接
        connection.close()


if __name__ == '__main__':
    main()
